package com.example.service.impl;

import com.example.mapper.NewsMapper;
import com.example.pojo.News;
import com.example.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.time.LocalDateTime;
import java.util.List;

@Service
public class NewsServiceImpl implements NewsService {
    @Autowired
    private NewsMapper newsMapper;

    @Override
    public News getNewsById(Integer id) {
        return newsMapper.findById(id);
    }

    //获取新闻列表
    @Override
    public List<News> getNewsList() {
        return newsMapper.findAll();
    }

    //根据新闻分类id获取新闻
    @Override
    public List<News> findByCategoryId(Integer categoryId) {
        return newsMapper.findByCategoryId(categoryId);
    }

    //根据新闻id删除新闻
    @Override
    public void deleteById(Integer id) {
        newsMapper.deleteById(id);
    }

    //添加新闻
    @Override
    public void add(News news) {
        news.setPublishTime(LocalDateTime.now());
        Integer categoryId = newsMapper.findCategoryIdByName(news.getCategoryName());
        if(categoryId != null){
            news.setCategoryId(categoryId);
            newsMapper.insert (news);
        }else {
            throw new IllegalArgumentException("分类名称不存在");
        }
        Integer newsId = news.getId();
        newsMapper.insertNewsCategoryRelation(newsId,categoryId);

    }

    @Override
    public void updateById(News news) {
        Integer categoryId = newsMapper.findCategoryIdByName(news.getCategoryName());
        news.setCategoryId(categoryId);
        newsMapper.updateById(news);
    }

}

